package com.xoa.dev.pz.service;

import com.xoa.dao.common.SysCodeMapper;

import com.xoa.model.common.SysCode;

import com.xoa.model.users.Users;
import com.xoa.dev.pz.dao.MenuJdtMapper;
import com.xoa.dev.pz.dao.PzHouseMapper;
import com.xoa.dev.pz.dao.PzHouseRentMapper;
import com.xoa.dev.pz.dao.PzHouseServiceMapper;
import com.xoa.dev.pz.model.PzHouse;
import com.xoa.dev.pz.model.PzHouseRent;
import com.xoa.dev.pz.model.PzHouseWithBLOBs;
import com.xoa.service.users.UsersService;
import com.xoa.dao.party.GridInfoMapper;
import com.xoa.model.party.GridInfo;
import com.xoa.util.DateFormat;
import com.xoa.util.ExcelUtil;
import com.xoa.util.ToJson;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.log.FileUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.netdisk.CheckAll;
import com.xoa.util.page.PageParams;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class PzHouseRentService {
    @Autowired
    private PzHouseRentMapper pzHouseRentMapper;

    @Autowired
    private UsersService usersService;

    @Autowired
    private PzHouseServiceMapper pzHouseServiceMapper;

    @Autowired
    private PzHouseMapper pzHouseMapper;

    @Autowired
    private SysCodeMapper sysCodeMapper;

    @Autowired
    private GridInfoMapper gridInfoMapper;

    @Autowired
    private MenuJdtMapper menuJdtMapper;

    /**
     * 增加
     * @param pzHouseRent
     * @return
     */
    @Transactional
    public ToJson insetRent(PzHouseRent pzHouseRent){
        ToJson toJson=new ToJson(1,"error");
        int temp=pzHouseRentMapper.insertSelective(pzHouseRent);
        if(temp>0){
            toJson.setFlag(0);
            toJson.setMsg("增加成功");
        }
        return toJson;

    }

    /**
     * 删除
     * @param rentId
     * @return
     */
    @Transactional
    public ToJson deleteRent(int rentId){
        ToJson toJson =new ToJson(1,"error");
        int temp=pzHouseRentMapper.deleteByPrimaryKey(rentId);
        temp+=pzHouseServiceMapper.delServiceByRentId(rentId);
        if(temp>0){
            toJson.setFlag(0);
            toJson.setMsg("删除成功");
        }
        return toJson;

    }

    /**
     * 修改
     * @param pzHouseRent
     * @return
     */
    @Transactional
    public ToJson updataRent(PzHouseRent pzHouseRent){
        ToJson toJson=new ToJson(1,"error");
        int temp=pzHouseRentMapper.updateByPrimaryKeySelective(pzHouseRent);
        if(temp>0){
            toJson.setFlag(0);
            toJson.setMsg("修改成功");
        }
        return toJson;

    }

    /**
     * 主键查询
     * @param rentId
     * @return
     */

    @Transactional
    public ToJson selectRentByrentId(int rentId){
        ToJson<PzHouseRent> toJson=new ToJson<PzHouseRent>(1,"error");
        PzHouseRent pzHouseRent=pzHouseRentMapper.selectByPrimaryKey(rentId);
        if(!"".equals(pzHouseRent.getRentUse())){
//            code/GetDropDownBox             RENT_USE
//                    sysCodeMapper.getSysCode("RENT_USE");
            List<SysCode> list = sysCodeMapper.getSysCode("RENT_USE");
            for(SysCode sysCode1:list){
               if(pzHouseRent.getRentUse().equals(sysCode1.getCodeNo())){
                   pzHouseRent.setRentUseStr(sysCode1.getCodeName());
               }
            }
        }
        if(pzHouseRent!=null){
            toJson.setObject(pzHouseRent);
            toJson.setFlag(0);
            toJson.setMsg("success");
        }
        return toJson;
    }

    /**
     * 关注度降序查询
     * @return
     */
    @Transactional
    public ToJson selectRentOrderByrentConcern(Integer page, Integer pageSize, boolean useFlag, PzHouseRent pzHouseRent, int output, HttpServletRequest request, HttpServletResponse response){
        ToJson<PzHouseRent> toJson=new ToJson<PzHouseRent>(1,"error");
        PageParams pageParams=new PageParams();
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        pageParams.setUseFlag(useFlag);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("page", pageParams);

        try {
            Map<String,Object> param=new Hashtable<String, Object>();
            Users user= SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());
            param.put("userId", user.getUserId());
            param.put("userPriv", user.getUserPriv());
            param.put("deptId", user.getDeptId());
            String menuModel=menuJdtMapper.selMenuByModel("3");
            if(!CheckAll.checkAll(menuModel,param)){
                pzHouseRent.setCreateUser(user.getUserId());
            }
            map.put("pzHouseRent",pzHouseRent);
            List<PzHouseRent> list=pzHouseRentMapper.selectRentOrderByrentConcern(map);
            for(PzHouseRent pzHouseRent1:list){
                if(!StringUtils.checkNull(pzHouseRent1.getGridUserId())){
                    pzHouseRent1.setUserName(usersService.getUserNameById(pzHouseRent1.getGridUserId()));
                }
                SysCode rentUseCode = sysCodeMapper.getSingleCode("RENT_USE", pzHouseRent1.getRentUse());
                if(rentUseCode!=null){
                    pzHouseRent1.setRentUseStr(rentUseCode.getCodeName());
                }
                SysCode rentConcernCode = sysCodeMapper.getSingleCode("RENT_CONCERN", pzHouseRent1.getRentConcern());
                if(rentConcernCode!=null){
                    pzHouseRent1.setRentConcernStr(rentConcernCode.getCodeName());
                }
                SysCode rentHiddenCode = sysCodeMapper.getSingleCode("RENT_HIDDEN", pzHouseRent1.getRentHidden());
                if(rentHiddenCode!=null){
                    pzHouseRent1.setRentHiddenStr(rentHiddenCode.getCodeName());
                }
                if(!StringUtils.checkNull(pzHouseRent1.getGridUserId())){
                    pzHouseRent1.setUserName(usersService.getUserNameById(pzHouseRent1.getGridUserId()));
                }
                SysCode purposeCode = sysCodeMapper.getSingleCode("HOUSE_PURPOSE", pzHouseRent1.getHousePurpose());
                if(purposeCode!=null){
                    pzHouseRent1.setHousePurposeStr(purposeCode.getCodeName());
                }
                SysCode makeupCode = sysCodeMapper.getSingleCode("HOUSE_MAKEUP", pzHouseRent1.getHouseMakeup());
                if(makeupCode!=null){
                    pzHouseRent1.setHouseMakeupStr(makeupCode.getCodeName());
                }
                SysCode applicationCode = sysCodeMapper.getSingleCode("HOUSE_APPLICATION", pzHouseRent1.getHouseApplication());
                if(applicationCode!=null){
                    pzHouseRent1.setHouseApplicationStr(applicationCode.getCodeName());
                }
                SysCode sourceCode = sysCodeMapper.getSingleCode("HOUSE_SOURCE", pzHouseRent1.getHouseSource());
                if(sourceCode!=null){
                    pzHouseRent1.setHouseSourceStr(sourceCode.getCodeName());
                }
            }
            if(output==1){
                for(PzHouseRent pzHouseRent1:list){
                    if(pzHouseRent1.getHouseType()!=null && pzHouseRent1.getHouseType().equals("0")){
                        pzHouseRent1.setHouseType("商品房");
                    }else{
                        pzHouseRent1.setHouseType("其他");
                    }
                    if(pzHouseRent1.getRentIs()!=null && pzHouseRent1.getRentIs()==2){
                        pzHouseRent1.setRentIsStr("是");
                    }else{
                        pzHouseRent1.setRentIsStr("否");
                    }
                    if(pzHouseRent1.getRentIsSafe()!=null && pzHouseRent1.getRentIsSafe()==2){
                        pzHouseRent1.setRentIsSafeStr("有");
                    }else{
                        pzHouseRent1.setRentIsSafeStr("无");
                    }
                    if(pzHouseRent1.getRentIsFire()!=null && pzHouseRent1.getRentIsFire()==2){
                        pzHouseRent1.setRentIsFireStr("有");
                    }else{
                        pzHouseRent1.setRentIsFireStr("无");
                    }
                    if(pzHouseRent1.getRentIsInsure()!=null && pzHouseRent1.getRentIsInsure()==2){
                        pzHouseRent1.setRentIsInsureStr("是");
                    }else{
                        pzHouseRent1.setRentIsInsureStr("否");
                    }
                    if(pzHouseRent1.getRentBeginTime()!=null){
                        pzHouseRent1.setRentBeginTimeStr(DateFormat.getDatestr(pzHouseRent1.getRentBeginTime()));
                    }
                    if(pzHouseRent1.getRentEndTime()!=null){
                        pzHouseRent1.setRentEndTimeStr(DateFormat.getDatestr(pzHouseRent1.getRentEndTime()));
                    }
                }
                HSSFWorkbook tableWork = ExcelUtil.makeExcelHead("出租房信息表", 15);
                String[] secondTitles = {"所属网络","建筑名称", "房屋区别类型","房屋地址","建筑用途","建成年份","房屋结构","房屋户型","建筑面积","房屋用途","房屋来源","房主","房主证件号码","房主联系方式","房主现居地址","备注", "关注程度","隐患类型","出租用途","租赁备案证号","是否出租","有无安全通道","有无消防通道","是否签订治安责任证书","承租人","承租开始时间","承租结束时间","承租人证件号码","承租人手机号"};
                HSSFWorkbook excelWork = ExcelUtil.makeSecondHead(tableWork, secondTitles);
                String[] beanProperty = {"gridName","houseName","houseType","houseLocation","housePurposeStr","houseYear","houseMakeupStr","houseStyle","houseArea","houseApplicationStr","houseSourceStr","houseUsername","houseIdcard","houseTelno","houseNowsite","houseMemo","rentConcernStr","rentHiddenStr","rentUseStr","rentNum","rentIsStr","rentIsSafeStr","rentIsFireStr","rentIsInsureStr","rentLessee","rentBeginTimeStr","rentEndTimeStr","rentLesseeLicense","rentLesseePhone"};
                HSSFWorkbook workbook = ExcelUtil.exportExcelData(excelWork, list, beanProperty);
                response.setContentType("text/html;charset=UTF-8");
                OutputStream out = response.getOutputStream();
                String filename = "出租房信息表.xls"; //考虑多语言
                filename = FileUtils.encodeDownloadFilename(filename,
                        request.getHeader("user-agent"));
                response.setContentType("application/vnd.ms-excel");
                response.setHeader("content-disposition",
                        "attachment;filename=" + filename);
                workbook.write(out);
                out.flush();
                out.close();
            }

            toJson.setObj(list);
            toJson.setTotleNum(pzHouseRentMapper.selectSize(pzHouseRent));
            toJson.setFlag(0);
            toJson.setMsg("success");
        }catch (Exception e){
            e.printStackTrace();
        }
        return toJson;
    }

    /**
     * 创建作者:   牛江丽
     * 创建日期:   2017年12月11日 下午16:02:00
     * 方法介绍:   出租房导入
     * 参数说明:
     * 返回值说明:
     */
    @Transactional
    public ToJson<PzHouseRent> inputPzHouseRent(HttpServletRequest request, HttpServletResponse response, MultipartFile file, HttpSession session) {
        ToJson<PzHouseRent> json = new ToJson<PzHouseRent>(1, "error");
        try {
            //判读当前系统
            //读取配置文件
            ResourceBundle rb = ResourceBundle.getBundle("upload");
            //String name = rb.getString("mysql.driverClassName");
            String osName = System.getProperty("os.name");
            StringBuffer path = new StringBuffer();
            if (osName.toLowerCase().startsWith("win")) {
                path = path.append(rb.getString("upload.win"));
            } else {
                path = path.append(rb.getString("upload.linux"));
            }
            if (file.isEmpty()) {
                json.setMsg("请上传文件！");
                return json;
            } else {
                int count=0;
                String fileName = file.getOriginalFilename();
                if (fileName.endsWith(".xls") || fileName.endsWith(".xlsx")) {
                    String uuid = UUID.randomUUID().toString();
                    uuid = uuid.replaceAll("-", "");
                    int pos = fileName.indexOf(".");
                    String extName = fileName.substring(pos);
                    String newFileName = uuid + extName;
                    File dest = new File(path.toString(), newFileName);
//                    file.transferTo(dest);
                    //将文件上传成功后进行读取文件
                    //进行读取的路径
                    //String readPath = path.append(newFileName).toString();'
                    String readPath = path.append(System.getProperty("file.separator")).append(newFileName).toString();
//                    InputStream in = new FileInputStream(readPath);
                    InputStream in =  file.getInputStream();
                    HSSFWorkbook excelObj = new HSSFWorkbook(in);
                    HSSFSheet sheetObj = excelObj.getSheetAt(0);
                    Row rowObj = null;
                    int lastRowNum = sheetObj.getLastRowNum();
                    int inputFail=0;
                    int inputSuccess=0;
                    String faillReason="";
                    for (int i = 1; i <= lastRowNum; i++) {
                        rowObj = sheetObj.getRow(i);
                        if (rowObj != null) {
                            Cell c0 = rowObj.getCell(0);
                            Cell c1 = rowObj.getCell(1);
                            Cell c2 = rowObj.getCell(2);
                            Cell c3 = rowObj.getCell(3);
                            Cell c4 = rowObj.getCell(4);
                            Cell c5 = rowObj.getCell(5);
                            Cell c6 = rowObj.getCell(6);
                            Cell c7 = rowObj.getCell(7);
                            Cell c8 = rowObj.getCell(8);
                            Cell c9 = rowObj.getCell(9);
                            Cell c10 = rowObj.getCell(10);
                            Cell c11 = rowObj.getCell(11);
                            Cell c12 = rowObj.getCell(12);
                            Cell c13 = rowObj.getCell(13);
                            Cell c14 = rowObj.getCell(14);
                            Cell c15 = rowObj.getCell(15);
                            Cell c16 = rowObj.getCell(16);

                            PzHouseWithBLOBs pzHouse = new PzHouseWithBLOBs();
                            GridInfo gridInfo = gridInfoMapper.selectByUGridName(c0.getStringCellValue());
                            if (gridInfo != null) {
                                pzHouse.setGridId(gridInfo.getGridId());
                            }
                            pzHouse.setHouseName(c1.getStringCellValue());
                            String c2Value = c2.getStringCellValue();
                            if (c2Value.equals("商品房")) {
                                pzHouse.setHouseType("0");
                            } else {
                                pzHouse.setHouseType("1");
                            }
                            pzHouse.setHouseLocation(c3.getStringCellValue());
                            pzHouse.setHouseLocationid(c4.getStringCellValue());
                            SysCode purposeCode = sysCodeMapper.getByName("HOUSE_PURPOSE",c5.getStringCellValue());
                            if(purposeCode!=null){
                                pzHouse.setHousePurpose(purposeCode.getCodeNo());
                            }if(c6!=null){
                                pzHouse.setHouseYear(c6.getStringCellValue());
                            }
                            SysCode makeupCode = sysCodeMapper.getByName("HOUSE_MAKEUP", c7.getStringCellValue());
                            if(makeupCode!=null){
                                pzHouse.setHouseMakeup(makeupCode.getCodeNo());
                            }
                            pzHouse.setHouseStyle(c8.getStringCellValue());
                            pzHouse.setHouseArea(c9.getStringCellValue());
                            SysCode applicationCode = sysCodeMapper.getByName("HOUSE_APPLICATION", c10.getStringCellValue());
                            if(applicationCode!=null){
                                pzHouse.setHouseApplication(applicationCode.getCodeNo());
                            }

                            SysCode sourceCode = sysCodeMapper.getByName("HOUSE_SOURCE", c11.getStringCellValue());
                            if(sourceCode!=null){
                                pzHouse.setHouseSource(sourceCode.getCodeNo());
                            }if(c12!=null){
                                pzHouse.setHouseUsername(c12.getStringCellValue());
                            }if(c13!=null){
                                pzHouse.setHouseIdcard(c13.getStringCellValue());
                            }if(c15!=null){
                                pzHouse.setHouseNowsite(c15.getStringCellValue());
                            }if(c16!=null){
                                pzHouse.setHouseMemo(c16.getStringCellValue());
                            }if(c14!=null){
                                pzHouse.setHouseTelno(Long.valueOf(c14.getStringCellValue()));
                            }
                            Cell c17 = rowObj.getCell(17);
                            Cell c18 = rowObj.getCell(18);
                            Cell c19 = rowObj.getCell(19);
                            Cell c20 = rowObj.getCell(20);
                            Cell c21 = rowObj.getCell(21);
                            Cell c22 = rowObj.getCell(22);
                            Cell c23 = rowObj.getCell(23);
                            Cell c24 = rowObj.getCell(24);
                            Cell c25 = rowObj.getCell(25);
                            Cell c26 = rowObj.getCell(26);
                            Cell c27 = rowObj.getCell(27);
                            Cell c28 = rowObj.getCell(28);
                            Cell c29 = rowObj.getCell(29);
                            PzHouseRent pzHouseRent = new PzHouseRent();
                            SysCode concertCode = sysCodeMapper.getByName("RENT_CONCERN",  c17.getStringCellValue());
                            if(concertCode!=null){
                                pzHouseRent.setRentConcern(concertCode.getCodeNo());
                            }
                            SysCode hiddenCode = sysCodeMapper.getByName("RENT_HIDDEN", c18.getStringCellValue());
                            if(hiddenCode!=null){
                                pzHouseRent.setRentHidden(hiddenCode.getCodeNo());
                            }
                            SysCode UseCode = sysCodeMapper.getByName("RENT_USE", c19.getStringCellValue());
                            if(UseCode!=null){
                                pzHouseRent.setRentUse(UseCode.getCodeNo());
                            }
                            if(c20!=null){
                                pzHouseRent.setRentNum(c20.getStringCellValue());
                            }
                            if(!StringUtils.checkNull(c21.getStringCellValue())&&c21.getStringCellValue().equals("是")){
                                pzHouseRent.setRentIs(2);
                            }else{
                                pzHouseRent.setRentIs(1);
                            }
                            if(!StringUtils.checkNull(c22.getStringCellValue())&&c22.getStringCellValue().equals("有")){
                                pzHouseRent.setRentIsSafe(2);
                            }else{
                                pzHouseRent.setRentIsSafe(1);
                            }
                            if(!StringUtils.checkNull(c23.getStringCellValue())&&c23.getStringCellValue().equals("有")){
                                pzHouseRent.setRentIsFire(2);
                            }else{
                                pzHouseRent.setRentIsFire(1);
                            }
                            if(!StringUtils.checkNull(c24.getStringCellValue())&&c24.getStringCellValue().equals("是")){
                                pzHouseRent.setRentIsInsure(2);
                            }else{
                                pzHouseRent.setRentIsInsure(1);
                            }
                            pzHouseRent.setRentLessee(c25.getStringCellValue());
                            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
                            if(c26!=null){
                                pzHouseRent.setRentBeginTime(sdf.parse(c26.getStringCellValue()));
                            }if(c27!=null){
                                pzHouseRent.setRentEndTime(sdf.parse(c27.getStringCellValue()));
                            }if(c28!=null){
                                pzHouseRent.setRentLesseeLicense(c28.getStringCellValue());
                            }if(c29!=null){
                                pzHouseRent.setRentLesseePhone(c29.getStringCellValue());
                            }
                            Users user= SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());
                            if(pzHouse.getGridId()!=null && !StringUtils.checkNull(pzHouse.getHouseLocation()) && !StringUtils.checkNull(pzHouse.getHouseUsername()) && !StringUtils.checkNull(pzHouse.getHouseIdcard()) && pzHouse.getHouseTelno()!=null){
                                PzHouse house=pzHouseMapper.selHouseByLocation(pzHouse.getHouseLocation());
                                if (!StringUtils.checkNull(pzHouseRent.getRentConcern()) && !StringUtils.checkNull(pzHouseRent.getRentUse()) && !StringUtils.checkNull(pzHouseRent.getRentLessee()) && pzHouseRent.getRentBeginTime() != null && pzHouseRent.getRentEndTime() != null && !StringUtils.checkNull(pzHouseRent.getRentLesseeLicense()) && !StringUtils.checkNull(pzHouseRent.getRentLesseePhone())){
                                    pzHouse.setHouseIsRent("2");
                                }else{
                                    pzHouse.setHouseIsRent("1");
                                }
                               if(house==null) {
                                   pzHouse.setCreateUser(user.getUserId());
                                   pzHouse.setCreateTime(DateFormat.getDatestr(new Date()));
                                   count+=pzHouseMapper.insertSelective(pzHouse);
                               }else {
                                   pzHouse.setHouseId(house.getHouseId());
                                   count+=pzHouseMapper.upByLocation(pzHouse);
                               }
                                if(!StringUtils.checkNull(pzHouseRent.getRentConcern())&&!StringUtils.checkNull(pzHouseRent.getRentUse())&&!StringUtils.checkNull(pzHouseRent.getRentLessee())&&pzHouseRent.getRentBeginTime()!=null&&pzHouseRent.getRentEndTime()!=null&&!StringUtils.checkNull(pzHouseRent.getRentLesseeLicense())&&!StringUtils.checkNull(pzHouseRent.getRentLesseePhone())) {
                                   if(count>0){
                                       if(pzHouseRentMapper.selRentByHouseId(pzHouse.getHouseId())==null) {
                                           pzHouseRent.setCreateUser(user.getUserId());
                                           pzHouseRent.setCreateTime(DateFormat.getDatestr(new Date()));
                                           pzHouseRent.setRentHouseId(pzHouse.getHouseId());
                                           pzHouseRentMapper.insertSelective(pzHouseRent);
                                       }else {
                                           pzHouseRent.setRentHouseId(pzHouse.getHouseId());
                                           pzHouseRentMapper.updateRentByHouseId(pzHouseRent);
                                       }
                                   }
                                }
                            }
                        }
                    }
                    json.setTotleNum(count);
                    json.setFlag(0);
                    json.setMsg("ok");
                    dest.delete();
                } else {
                    json.setMsg("0");//文件类型不正确
                    return json;
                }
            }
        } catch (Exception e) {
            json.setMsg(e.getMessage());
     /*       L.e("EduFixAssetsService inputFixAsserts:"+e);*/
            e.printStackTrace();
        }
        return json;
    }
}
